import callBaiduAPI from './BaiduTrans';

interface KeywordTranslation {
  inputElement: HTMLElement;
  translationElement: HTMLElement;
  colorId: string;
  keywordIndex: string | number;
  lastInputText: string;
  lastTranslationText: string;
  observer?: MutationObserver;
  isTranslating: boolean;
}

// Store active keyword translations
const activeKeywordTranslations: KeywordTranslation[] = [];

// 检查是否使用防抖
let useDebounce = true;
const debounceDelays: Record<string, number> = {};
const DEBOUNCE_TIME = 1000; // 1秒防抖延迟

/**
 * 直接调用百度翻译API进行关键词翻译
 */
async function translateKeyword(keywordData: KeywordTranslation, isReverse = false) {
  try {
    // 如果已经在翻译中，则跳过
    if (keywordData.isTranslating) {
      console.log(`跳过翻译，已有翻译在进行中: 关键词k${keywordData.keywordIndex}`);
      return;
    }
    
    keywordData.isTranslating = true;
    
    // 获取源和目标元素
    const sourceElement = isReverse ? keywordData.translationElement : keywordData.inputElement;
    const targetElement = isReverse ? keywordData.inputElement : keywordData.translationElement;
    
    // 获取要翻译的文本 - 处理不同的元素类型
    let text = '';
    if (sourceElement.tagName.toLowerCase() === 'input') {
      text = (sourceElement as HTMLInputElement).value || '';
    } else {
      text = sourceElement.innerText || sourceElement.textContent || '';
    }
    
    if (!text.trim()) {
      // 如果源为空，同样清空目标
      if (targetElement.isContentEditable) {
        targetElement.innerText = '';
      } else if (targetElement.tagName.toLowerCase() === 'input') {
        (targetElement as HTMLInputElement).value = '';
      } else {
        targetElement.textContent = '';
      }
      keywordData.isTranslating = false;
      return;
    }
    
    // 检查文本是否与上次相同
    const lastTextKey = isReverse ? 'lastTranslationText' : 'lastInputText';
    if (keywordData[lastTextKey] === text) {
      console.log(`检测到相同内容，跳过翻译: 关键词k${keywordData.keywordIndex}`);
      keywordData.isTranslating = false;
      return;
    }
    
    // 确定源语言和目标语言
    const targetLanguage = isReverse ? 'english' : 'chinese';
    
    console.log(`直接翻译: ${isReverse ? 'chinese -> english' : 'english -> chinese'}, 文本: ${text.substring(0, 30)}${text.length > 30 ? '...' : ''}, 关键词k${keywordData.keywordIndex}`);
    
    // 显示翻译中状态
    if (targetElement.isContentEditable) {
      targetElement.innerText = '翻译中...';
    } else if (targetElement.tagName.toLowerCase() === 'input') {
      // 输入框不显示"翻译中"
    } else {
      targetElement.textContent = '翻译中...';
    }
    
    // 调用百度API
    const translatedText = await callBaiduAPI(text, Number(keywordData.keywordIndex), targetLanguage as 'chinese' | 'english');
    
    // 更新缓存
    if (isReverse) {
      keywordData.lastTranslationText = text;
      keywordData.lastInputText = translatedText as string;
    } else {
      keywordData.lastInputText = text;
      keywordData.lastTranslationText = translatedText as string;
    }
    
    // 更新目标元素
    if (targetElement.isContentEditable) {
      targetElement.innerText = translatedText as string;
      targetElement.dispatchEvent(new Event('input', { bubbles: true }));
    } else if (targetElement.tagName.toLowerCase() === 'input') {
      (targetElement as HTMLInputElement).value = translatedText as string;
      // 触发input事件以确保Vue绑定的数据同步更新
      targetElement.dispatchEvent(new Event('input', { bubbles: true }));
    } else {
      targetElement.textContent = translatedText as string;
    }
    
    console.log(`直接翻译完成: ${isReverse ? 'chinese -> english' : 'english -> chinese'}, 关键词k${keywordData.keywordIndex}`);
  } catch (error) {
    console.error('关键词翻译错误:', error);
    // 简单的错误提示
    console.error(`翻译失败: 关键词k${keywordData.keywordIndex}`);
  } finally {
    keywordData.isTranslating = false;
  }
}

/**
 * 带防抖的翻译处理
 */
function handleTranslationWithDebounce(keywordData: KeywordTranslation, isReverse = false) {
  const key = `k${keywordData.keywordIndex}_${isReverse ? 'reverse' : 'forward'}`;
  
  // 如果使用防抖，先清除之前的定时器
  if (useDebounce) {
    if (debounceDelays[key]) {
      clearTimeout(debounceDelays[key]);
      delete debounceDelays[key];
    }
    
    // 设置新的定时器
    debounceDelays[key] = window.setTimeout(() => {
      translateKeyword(keywordData, isReverse);
      delete debounceDelays[key];
    }, DEBOUNCE_TIME) as unknown as number;
  } else {
    // 不使用防抖，直接翻译
    translateKeyword(keywordData, isReverse);
  }
}

/**
 * 创建和观察单个关键词输入和翻译元素
 */
function observeSingleKeyword(inputElement: HTMLElement, translationElement: HTMLElement) {
  // 获取颜色ID和关键词索引
  const colorId = inputElement.getAttribute('data-keyword-id') || '';
  const keywordIndex = inputElement.getAttribute('data-keyword-index') || '0';
  
  if (!keywordIndex) {
    console.error('无法获取关键词索引，跳过观察');
    return;
  }
  
  // 检查是否已经在观察这个关键词
  const existingIndex = activeKeywordTranslations.findIndex(
    k => k.keywordIndex.toString() === keywordIndex.toString()
  );
  
  if (existingIndex !== -1) {
    console.log(`已经在观察的关键词，更新引用: k${keywordIndex}`);
    const existing = activeKeywordTranslations[existingIndex];
    
    // 更新元素引用和colorId（以防颜色变化）
    existing.inputElement = inputElement;
    existing.translationElement = translationElement;
    existing.colorId = colorId;
    return;
  }
  
  console.log(`开始观察新的关键词: colorId=${colorId}, 索引: k${keywordIndex}`);
  
  // 创建新的关键词翻译数据
  const keywordData: KeywordTranslation = {
    inputElement,
    translationElement,
    colorId,
    keywordIndex,
    lastInputText: '',
    lastTranslationText: '',
    isTranslating: false
  };
  
  // 创建输入观察器 - 根据元素类型绑定不同的事件
  const handleInputChange = (event: Event) => {
    let text = '';
    if (inputElement.tagName.toLowerCase() === 'input') {
      text = (inputElement as HTMLInputElement).value || '';
    } else {
      text = inputElement.innerText || inputElement.textContent || '';
    }
    console.log(`关键词输入变化: k${keywordIndex}, 文本: ${text.substring(0, 30)}${text.length > 30 ? '...' : ''}`);
    handleTranslationWithDebounce(keywordData, false);
  };
  
  // 创建翻译观察器
  const handleTranslationChange = (event: Event) => {
    const text = (event.target as HTMLElement).innerText || (event.target as HTMLElement).textContent || '';
    console.log(`翻译输入变化: k${keywordIndex}, 文本: ${text.substring(0, 30)}${text.length > 30 ? '...' : ''}`);
    handleTranslationWithDebounce(keywordData, true);
  };
  
  // 绑定事件监听器 - 根据元素类型使用不同的事件
  if (inputElement.tagName.toLowerCase() === 'input') {
    inputElement.addEventListener('input', handleInputChange);
  } else {
    inputElement.addEventListener('input', handleInputChange);
  }
  
  translationElement.addEventListener('input', handleTranslationChange);
  
  // 存储观察器
  activeKeywordTranslations.push(keywordData);
}

/**
 * 更新DOM选择器，使用关键词索引而非颜色ID作为主要标识符
 */
function updateDomSelectors() {
  // 先清理已有的关键词翻译组
  const expiredKeywords = [...activeKeywordTranslations];
  activeKeywordTranslations.length = 0;
  
  // 查找所有当前存在的关键词输入和翻译元素（基于索引）
  const keywordInputs = document.querySelectorAll('.keyword-input[data-keyword-index]');
  
  console.log(`找到 ${keywordInputs.length} 个关键词输入`);
  
  // 为每个关键词创建新的翻译组
  keywordInputs.forEach((input) => {
    const index = input.getAttribute('data-keyword-index');
    if (!index) return;
    
    const colorId = input.getAttribute('data-keyword-id') || '';
    
    // 查找对应的翻译元素
    const translation = document.querySelector(`.keyword-translation[data-keyword-index="${index}"]`);
    if (translation) {
      console.log(`为关键词k${index}重新创建翻译组`);
      observeSingleKeyword(input as HTMLElement, translation as HTMLElement);
    }
  });
  
  // 为不再存在的关键词记录日志
  if (expiredKeywords.length > activeKeywordTranslations.length) {
    console.log(`清理了 ${expiredKeywords.length - activeKeywordTranslations.length} 个失效的关键词翻译组`);
  }
}

/**
 * 初始化关键词输入和翻译的观察
 */
export function initKeywordTranslator(disableDebounce = false) {
  useDebounce = !disableDebounce;
  
  console.log('正在初始化关键词翻译器...');
  
  // 查找所有当前存在的关键词输入和翻译元素
  setTimeout(() => {
    updateDomSelectors();
    
    // 创建DOM观察器，监听新添加的关键词元素
    const observer = new MutationObserver((mutations) => {
      let keywordElementsChanged = false;
      
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
          // 检查是否有新的关键词输入或翻译元素被添加或移除
          if (mutation.addedNodes.length > 0 || mutation.removedNodes.length > 0) {
            // 检查添加的节点是否包含关键词元素
            mutation.addedNodes.forEach((node) => {
              if (node.nodeType === Node.ELEMENT_NODE) {
                const element = node as HTMLElement;
                
                // 检查添加的元素或其子元素是否包含关键词元素
                if (element.classList.contains('keyword-input-group') || 
                    element.querySelector('.keyword-input-group') ||
                    element.classList.contains('keyword-input') ||
                    element.querySelector('.keyword-input') ||
                    element.classList.contains('keyword-translation') ||
                    element.querySelector('.keyword-translation')) {
                  keywordElementsChanged = true;
                }
              }
            });
            
            // 检查移除的节点是否包含关键词元素
            mutation.removedNodes.forEach((node) => {
              if (node.nodeType === Node.ELEMENT_NODE) {
                const element = node as HTMLElement;
                
                // 检查移除的元素或其子元素是否包含关键词元素
                if (element.classList.contains('keyword-input-group') || 
                    element.querySelector?.('.keyword-input-group') ||
                    element.classList.contains('keyword-input') ||
                    element.querySelector?.('.keyword-input') ||
                    element.classList.contains('keyword-translation') ||
                    element.querySelector?.('.keyword-translation')) {
                  keywordElementsChanged = true;
                }
              }
            });
          }
        }
      });
      
      // 如果检测到关键词元素变化，延迟执行更新
      if (keywordElementsChanged) {
        console.log('检测到关键词元素变化，将更新翻译组');
        setTimeout(() => {
          updateDomSelectors();
        }, 300);
      }
    });
    
    // 开始观察整个文档
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
    
    console.log('关键词翻译观察器已初始化');
    
    // 返回停止函数，但我们不会实际使用，因为我们希望观察器一直运行
    return () => {
      observer.disconnect();
      console.log('关键词翻译观察器已停止');
    };
  }, 300);
}

/**
 * 手动重新扫描所有关键词
 */
export function rescanKeywords() {
  console.log('手动重新扫描关键词元素');
  updateDomSelectors();
}

/**
 * 手动触发特定关键词的翻译
 */
export function triggerKeywordTranslation(keywordIndex: string | number, isReverse = false) {
  const keywordData = activeKeywordTranslations.find(k => 
    k.keywordIndex.toString() === keywordIndex.toString()
  );
  
  if (keywordData) {
    console.log(`手动触发翻译: k${keywordIndex}, 反向=${isReverse}`);
    translateKeyword(keywordData, isReverse);
  } else {
    console.error(`找不到关键词: k${keywordIndex}`);
  }
}

/**
 * 手动触发所有关键词的翻译
 */
export function triggerAllKeywordTranslations(isReverse = false) {
  console.log(`手动触发所有关键词翻译, 反向=${isReverse}`);
  
  activeKeywordTranslations.forEach(keywordData => {
    translateKeyword(keywordData, isReverse);
  });
}

// 导出一个简单的状态对象，方便调试
export const keywordTranslatorState = {
  getActiveKeywords: () => activeKeywordTranslations.map(k => ({ 
    colorId: k.colorId, 
    keywordIndex: k.keywordIndex,
    hasInput: Boolean(k.lastInputText),
    hasTranslation: Boolean(k.lastTranslationText)
  })),
  getKeywordCount: () => activeKeywordTranslations.length,
  clearKeywords: () => {
    activeKeywordTranslations.length = 0;
    console.log('已清空所有观察的关键词');
  }
}; 